# -* utf-8 -*-
"""
Created on Tue Feb 19 01:52:04 2019

@author: dmitrievsky
"""
import socket

from utils.constant_util import socketMes
from utils.logger import loger
from utils.thread_util import createThread


class sockets_server:
    def __init__(self, address='', port=9090):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.address = address
        self.port = port
        self.sock.bind((self.address, self.port))
        self.sock.listen(1)

    def startThread(self):
        loger.info("等待连接socket服务")
        while True:
            conn, addr = self.sock.accept()
            createThread(self.socketThread, args=(conn, addr,)).start()

    def socketThread(self, conn, addr):
        loger.info('socket客户端地址为:{0}'.format(addr))
        conn.send(('connect success').encode())

        while True:
            data = conn.recv(10000)
            if not data:
                break
            if socketMes() != "":
                conn.send(bytes(socketMes(), "utf-8"))
            else:
                conn.send(bytes("null", "utf-8"))

    def __del__(self):
        self.sock.close()


if __name__ == '__main__':
    sockets_server('127.0.0.1', 6661).startThread()
